package logic

import (
	"context"

	"jinrigaoping/rpc/sys/internal/model"
	"jinrigaoping/rpc/sys/internal/svc"
	"jinrigaoping/rpc/sys/sys"

	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
)

type SysRoleAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSysRoleAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SysRoleAddLogic {
	return &SysRoleAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *SysRoleAddLogic) SysRoleAdd(in *sys.SysRoleAddReq) (*sys.SysRoleAddRes, error) {

	if err := l.svcCtx.SysRoleModel.Trans(l.ctx, func(ctx context.Context, session sqlx.Session) error {

		result, err := l.svcCtx.SysRoleModel.TransInsert(ctx, session, &model.SysRole{
			RoleName: in.RoleName,
			Remark:   in.Remark,
		})
		if err != nil {
			return err
		}

		roleId, err := result.LastInsertId()
		if err != nil {
			return err
		}

		if len(in.MenuIdList) > 0 {
			var sysRoleMenuList = make([]model.SysRoleMenu, len(in.MenuIdList))
			for i, v := range in.MenuIdList {
				sysRoleMenuList[i] = model.SysRoleMenu{
					Id:     0,
					RoleId: roleId,
					MenuId: v,
				}
			}

			err = l.svcCtx.SysRoleMenuModel.TransInsertBatch(l.ctx, session, sysRoleMenuList)
			if err != nil {
				return err
			}
		}

		return nil
	}); err != nil {
		return nil, err
	}

	return &sys.SysRoleAddRes{}, nil
}
